//
//  BaseViewController.m
//  HigerGbos
//
//  Created by KevinMao on 14-5-21.
//  Copyright (c) 2014年 Jijesoft. All rights reserved.
//

#import "BaseViewController.h"
#import "LoginViewController.h"
#import "AppDelegate.h"
#import "FMUICreator.h"
#import "FMUMath.h"

#define smallViewWidth 750
#define smallViewHeight 560
#define IOS7_OR_LATER   ( [[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending )

@interface BaseViewController ()

@end

@implementation BaseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
}

-(void)dealloc
{
    [self.asiFDR setDelegate:nil];
}

-(IBAction)backAction:(id)sender
{
//    [self dismissModalViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        [self setNeedsStatusBarAppearanceUpdate];
        
        self.edgesForExtendedLayout= UIRectEdgeNone;
        
        self.navigationController.navigationBar.translucent = NO;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 旋转
- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight){
        return YES;
    }
    return NO;
}

#pragma mark - Base
- (BOOL)isEmptyString:(NSString *)_str
{
    if ([_str isKindOfClass:[NSNull class]]) {
        return YES;
    }
    
    if ([_str isEqualToString:@""]) {
        return YES;
    }
    if (_str == nil) {
        return YES;
    }
    if (_str == NULL) {
        return YES;
    }
    if ((NSNull*)_str == [NSNull null]) {
        return YES;
    }
    return NO;
}

- (BOOL)isEmptyStringFilterBlank:(NSString *)_str
{
    if ([self isEmptyString:_str]) {
        return YES;
    }
    
    NSMutableString *string = [NSMutableString stringWithFormat:@"%@",_str];
    [string replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, string.length)];
    [string replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:NSMakeRange(0, string.length)];
    if (string.length == 0) {
        return YES;
    }
    return NO;
}

#pragma mark - 公共处理方法

- (void)errorForAuthentication
{
    LoginViewController *vc = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:vc];
    [UIApplication sharedApplication].keyWindow.rootViewController = navi;
    vc.view.alpha = 0.0;
    [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        vc.view.alpha = 1.0;
    } completion:^(BOOL finished) {
//        [[BaseMenuView shared] releaseMenu:YES];
    }];
}

- (UIButton *)setBackButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 0, 44, 40)];
//    [button setImageEdgeInsets:UIEdgeInsetsMake(10, -14, 10, 14)];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [button setImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateHighlighted];
    
    return button;
}

//设置左边的返回按钮
- (void)setLeftBackButton
{
    [self setLeftButton:[self setBackButton] action:@selector(backButtonPressed:)];
}

- (void)setLeftBackButtonAction:(SEL)selector
{
    [self setLeftButton:[self setBackButton] action:selector];
}


//设置左边的返回按钮(图片按钮)
- (void)setLeftButtonWithImageName:(NSString*)imageName action:(SEL)selector
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 0, 44, 40)];
    [button setImageEdgeInsets:UIEdgeInsetsMake(10, 16.5, 10, 16.5)];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [self setLeftButton:button action:selector];
}

//设置左边的返回按钮(文字按钮)
- (void)setLeftButtonWithTitle:(NSString*)title action:(SEL)selector
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    UIFont* font = [UIFont fontWithName:@"Helvetica-Light" size:15.0];
    CGFloat width = [title sizeWithFont:font].width;
    [button setFrame:CGRectMake(8, 8, width, 20)];
    button.titleLabel.font = font;
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    
    [self setLeftButton:button action:selector];
}

//设置左边的返回按钮(通用按钮)
- (void)setLeftButton:(UIButton*)button action:(SEL)selector
{
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 40)];
    contentView.clipsToBounds = YES;
    contentView.backgroundColor = [UIColor clearColor];
    [contentView addSubview:button];
    CGRect rect = button.frame;
    rect.origin.x = 0;
    rect.origin.y = (CGRectGetHeight(contentView.frame) - CGRectGetHeight(button.frame))/2.0;
    button.frame = rect;
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:contentView];
    
    self.navigationItem.leftBarButtonItem = barButtonItem;//[[UIBarButtonItem alloc] initWithCustomView:button];
}


//设置中间的文本标题
- (void)setTitleViewWithText:(NSString*)text
{
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleLabel.text = text;
    titleLabel.textColor = RGBColor(255.0, 255.0, 255.0);
    titleLabel.center = CGPointMake(self.view.frame.size.width/2, 44);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:20];
    titleLabel.backgroundColor = [UIColor clearColor];
    self.navigationItem.titleView = titleLabel;
}


//设置右边的按钮(文字按钮), 可以指定按钮水平位置
- (void)setRightButtonWithTitle:(NSString*)title action:(SEL)selector
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    UIFont* font = [UIFont fontWithName:@"Helvetica-Light" size:15.0];
    CGFloat width = [title sizeWithFont:font].width;
    [button setFrame:CGRectMake(0, 0, width, 20)];
    button.titleLabel.font = font;
    
    
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self setRightButton:button  action:selector];
}

//设置右边的按钮(图片按钮), 可以指定按钮水平位置
- (void)setRightButtonWithImageName:(NSString*)imageName action:(SEL)selector
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 44, 44);
    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [self setRightButton:button  action:selector];
}

- (void)setRightButtonWithNormarlImageName:(NSString*)normarName highlightedImageName:(NSString *)highlightedName action:(SEL)selector
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 44, 44);
    [button setImage:[UIImage imageNamed:normarName] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:highlightedName] forState:UIControlStateHighlighted];
    UIImage *img = [UIImage imageNamed:normarName];
    [button setImageEdgeInsets:UIEdgeInsetsMake((44 - img.size.height)/2.0, 44 - 4 - img.size.width, (44 - img.size.height)/2.0, 4)];
    [self setRightButton:button  action:selector];
}

//设置右边的按钮
- (void)setRightButton:(UIButton*)button action:(SEL)selector
{
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    UIView *customView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    customView.backgroundColor = [UIColor clearColor];
    customView.clipsToBounds = NO;
    button.center = customView.center;
    [customView addSubview:button];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:customView];
}


/*
 *  btnStrs 里面 vo 是dic
 *  dic 有 两个key 一个 normalImage  一个title
 */

- (void)setRightButtons:(NSArray *)btnStrs
{
    if(btnStrs == nil)
    {
        self.navigationItem.rightBarButtonItems = nil;
        return;
    }
    
    NSMutableArray *items = [[NSMutableArray alloc]init];
    for (int i = 0; i < btnStrs.count; i ++) {
        NSString *buttonTitle = [btnStrs objectAtIndex:i] ;//[btnStrs objectAtIndex:i];

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 40, 19);
        btn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        
        btn.titleLabel.textColor = [UIColor whiteColor];
        [btn setTitle:buttonTitle forState:UIControlStateNormal];
        btn.tag = i;
        [btn addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:btn];
        [items addObject:item];
    }
    
    
    self.navigationItem.rightBarButtonItems = items;
}

- (void)setRightButtonImages:(NSArray *)images
{
    
    if(images == nil)
    {
        self.navigationItem.rightBarButtonItems = nil;
        return;
    }
    
    NSMutableArray *items = [[NSMutableArray alloc]init];
    for (int i = 0; i < images.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 20, 19);
        UIImage *image = [UIImage imageNamed:[images objectAtIndex:i]];
        [btn setImage:image forState:UIControlStateNormal];
        btn.tag = i;
        [btn addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:btn];
        [items addObject:item];
    }
    self.navigationItem.rightBarButtonItems = items;
}



//返回按钮的响应事件
- (void)backButtonPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonAction:(id)sender
{
    
}

#pragma mark - Present

-(void)presentViewControllerInFullRect:(BaseViewController*)viewController
{
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
    navigationController.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:navigationController animated:YES completion:^{
        
    }];
//    navigationController.navigationBarHidden = YES;
}

-(void)presentViewControllerInSmallRect:(BaseViewController*)viewController
{
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
    
    navigationController.modalPresentationStyle = UIModalPresentationFormSheet;
    [navigationController disablesAutomaticKeyboardDismissal];
    [self presentViewController:navigationController animated:YES completion:^{
        
    }];
    
    navigationController.view.superview.autoresizingMask =
    UIViewAutoresizingFlexibleTopMargin |
    UIViewAutoresizingFlexibleBottomMargin;
    
    navigationController.view.superview.frame = CGRectMake(
                                                           navigationController.view.superview.frame.origin.x,
                                                           navigationController.view.superview.frame.origin.y,
                                                           smallViewWidth,
                                                           smallViewHeight
                                                           );
    navigationController.view.superview.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2);
    
}


#pragma navibar
#pragma mark - FMNavigationBar delegate
-(void)fmNavigationBar:(FMNavigationBar*)fmNavigationBar didSelectedAtTag:(NSUInteger)tag
{
    //0，返回按钮
    if (tag == 0)
    {
        [self backAction:nil];
        return ;
    }
    
    //1，右边按钮
    //子类
}

#pragma mark - navigationBar
//中间titleView
- (void)setNavTitle:(NSString *)title
{
    if (self.navigationItem) {
        [self setNavTitleView:nil];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
        if (IOS7_OR_LATER) {
//            NSDictionary *dict = [NSDictionary dictionaryWithObject:[UIColor blackColor] forKey:UITextAttributeTextColor];UITextAttributeFont
            NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[[UIColor darkGrayColor],[UIFont boldSystemFontOfSize:24.0]] forKeys:@[UITextAttributeTextColor,UITextAttributeFont]];
            self.navigationController.navigationBar.titleTextAttributes = dict;
            self.navigationItem.title = title;
            return;
        }
#endif
        UILabel *titleLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 180, 44)];
        titleLb.backgroundColor = [UIColor clearColor];
        titleLb.font = [UIFont boldSystemFontOfSize:24.0];
        titleLb.textColor = [UIColor redColor];
        titleLb.textAlignment = NSTextAlignmentCenter;
        titleLb.text = title;
        [self setNavTitleView:titleLb];
    }
}

- (void)setNavTitleView:(UIView *)titleView
{
    if (self.navigationItem) {
        self.navigationItem.titleView = titleView;
    }
}

//左侧返回
- (void)setNavBackButton:(NSString *)btnStr
{
    FMButtonItemAttribute *attr = [[FMButtonItemAttribute alloc] init];
    
    if (self.navigationItem) {
        UIImage *rBtnImg = [UIImage imageNamed:btnStr];
        if (rBtnImg) {
            attr.title = nil;
            attr.defaultIcon = btnStr;
        }
        else {
            attr.title = btnStr;
            attr.itemDefaultColor = [UIColor colorWithRed:128/255 green:128/255 blue:128/255 alpha:1.0];
            attr.font = [UIFont systemFontOfSize:15.0];
            attr.defaultIcon = nil;
        }
        self.navigationItem.leftBarButtonItem = [FMUICreator createBarButtonItem:attr target:self selector:@selector(navBackButtonAction:)];
    }
    
    if ([self isEmptyString:btnStr]) {
        self.navigationItem.leftBarButtonItem=nil;
    }
}

- (void)navBackButtonAction:(id)sender
{
    UIControl *ctrl = (UIControl *)sender;
    NSUInteger tag = ctrl.tag + 1;
    [self navBackButtonActionAtTag:tag];
}

- (void)navBackButtonActionAtTag:(NSUInteger)tag
{
    //tag从一开始
//    [self dismissModalViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

//右侧按钮
- (void)setNavRightButton:(NSString *)btnStr
{
    FMButtonItemAttribute *attr = [[FMButtonItemAttribute alloc] init];
    if (self.navigationItem) {
        UIImage *rBtnImg = [UIImage imageNamed:btnStr];
        if (rBtnImg) {
            attr.title = nil;
            attr.defaultIcon = btnStr;
        }
        else {
            attr.title = btnStr;
            attr.itemDefaultColor = [UIColor blueColor];
            attr.font = [UIFont boldSystemFontOfSize:20.0];
            attr.defaultIcon = nil;
        }
        self.navigationItem.rightBarButtonItem = [FMUICreator createBarButtonItem:attr target:self selector:@selector(navRightButtonAction:)];
    }
    
    if ([self isEmptyString:btnStr]) {
        self.navigationItem.rightBarButtonItem=nil;
    }
}

- (void)setNavRightButtons:(NSArray *)btnStrs
{
    if (btnStrs.count < 1 || !self.navigationItem) {
        return;
    }
    
    UIView *rightView = [[UIView alloc] init];
    rightView.frame = CGRectMake(0, 0, 0, 44);
    CGFloat width = 0.0;
    for (int i = 0; i < btnStrs.count; i ++) {
        NSString *btnStr = [btnStrs objectAtIndex:i];
        FMButtonItemAttribute *attr = [[FMButtonItemAttribute alloc] init];
        attr.tag = i;
        UIImage *rBtnImg = [UIImage imageNamed:btnStr];
        if (rBtnImg) {
            attr.title = nil;
            attr.defaultIcon = btnStr;
        }
        else {
            attr.title = btnStr;
            attr.itemDefaultColor = [UIColor darkGrayColor];
            attr.font = [UIFont systemFontOfSize:16.0];
            attr.defaultIcon = nil;
        }
        UIButton *btn = [FMUICreator createButton:attr target:self Selector:@selector(navRightButtonAction:)];
        CGRect btnFrame = btn.frame;
        btnFrame.origin.x = width + i*5;
        btn.frame = btnFrame;
        
        CGPoint btnCenter = btn.center;
        btnCenter.y = rightView.center.y;
        btn.center = btnCenter;
        
        [rightView addSubview:btn];
        
        width = CGRectGetMaxX(btnFrame);
    }
    rightView.frame = FMURectSetWidth(rightView.frame, width);
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:rightView];
    self.navigationItem.rightBarButtonItem = item;
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
    if (IOS7_OR_LATER) {
        return;
    }
#endif
    
    //调整titleView
    UIView *titleView = self.navigationItem.titleView;
    UINavigationBar *navBar = self.navigationController.navigationBar;
    CGRect tf = titleView.frame;
    CGRect nf = navBar.frame;
    CGFloat rw = nf.size.width - 2*(width + 20);
    if (rw < tf.size.width) {
        tf.size.width = rw;
        titleView.frame = tf;
        self.navigationItem.titleView = titleView;
    }
}

- (void)navRightButtonAction:(id)sender
{
    UIControl *ctrl = (UIControl *)sender;
    NSUInteger tag = ctrl.tag + 1;
    [self navRightButtonActionAtTag:tag];
}

- (void)navRightButtonActionAtTag:(NSUInteger)tag
{
    //字类实现
    //tag从一开始
}

-(void)getCarList
{
    [gAlert showLoading:nil delegate:nil];
    
//    [MBProgressHUD showHUDAddedTo:self.view animated:NO];
    
    [CommunicateWithService communicateWithServiceApiName:@"vehSelectList.do" finishSelector:@selector(getCarListFinished:) failSelector:@selector(getCarListFailed:) delegateObj:self];
}

//请求服务器成功
-(void)getCarListFinished:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
//    [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
    if (request.responseStatusCode == 400) {
        //textView.text = @"Invalid code";
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
        //textView.text = @"Code already used";
    } else if (request.responseStatusCode == 200) {
        NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json 2 dic
        
        NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
        
        NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
        
        NSDictionary *strDicData=(NSDictionary *)[strDic objectForKey:@"resultData"];//服务器返回数据字典
        
        if ([flag isEqualToString:@"1001"]) {
            NSUserDefaults *userInfo=[NSUserDefaults standardUserDefaults];
            
            [userInfo setObject:(NSMutableArray *)[strDicData objectForKey:@"domainList"] forKey:@"domainList"];
            [userInfo setObject:(NSMutableArray *)[strDicData objectForKey:@"groupList"] forKey:@"groupList"];
            [userInfo setObject:(NSMutableArray *)[strDicData objectForKey:@"modelList"] forKey:@"modelList"];
            [userInfo setObject:(NSMutableArray *)[strDicData objectForKey:@"phaseList"] forKey:@"phaseList"];
            [userInfo setObject:(NSMutableArray *)[strDicData objectForKey:@"plantList"] forKey:@"plantList"];
            [userInfo setObject:(NSMutableArray *)[strDicData objectForKey:@"seriesList"] forKey:@"seriesList"];
            [userInfo setObject:(NSMutableArray *)[strDicData objectForKey:@"dateList"] forKey:@"dateList"];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_IS_LOAD_CAR_LIST object:nil];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_INIT_SEARCH_DATA object:nil];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_INIT_DATA object:nil];
        }
        else if ([flag isEqualToString:@"1002"])
        {
            [gAlert show:msg inView:self.view delegate:nil];
        }
    }
}

//请求服务器失败
-(void)getCarListFailed:(ASIHTTPRequest *)request
{
//    NSLog(@"%@",request.error);
    [gAlert dismiss];
//    [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
    [NetworkCheck checkNetwork:self];//检查网络
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_NO_NETWORK object:nil];
}

@end





